/**
 * Created by 功振 on 2016/4/5.
 */
module.controller('ServiceListController',
    function ($scope, $rootScope,$stateParams, $uibModal, $state,$interval, $log, k8sService, $http, $cookies, $mdBottomSheet,svcCommonService,clusterService,utilService,$mdDialog,$filter) {
        var user = $cookies.get("username"),
            _deregister_udp_info = undefined,
            _getPodst_to = undefined,
            _podTracer = undefined ,
            promise = undefined,
            selected = null,
            previous = null,
            tabs = [
                { title: '默认集群',value:'default'}
            ],
            hashMap = {
                set : function(key,value){this[key] = value},
                get : function(key){return this[key]},
                contains : function(key){return this.get(key) == null?false:true},
                remove : function(key){delete this[key]},
                clear:function(){
                    //console.log("clear the map") ;
                    for(var i in this){
                        if( typeof  this[i] =="function" ){
                            continue ;
                        }
                        this.remove( i ) ;
                    }
                }
            } ;
        loadClusterInfo(); //加载集群信息
        $scope._podTracerCount = 0 ;
        $scope.username = user;
        $scope.animationsEnabled = true;
        $scope.services = undefined;
        $scope.projects=[];
        $scope.curPod={}

        $rootScope.curScope = $scope;
        $scope.reloaded = true ;
        if(  !$scope.status ){
            $scope.status = undefined ; //记录原来的状态 TODO 只能在当前scope下有效。刷新会导致重新初始化
        }
        //DEBUG test autoscale pod
        var autoScale = undefined ;

        $scope.selectedIndex = 0 ; //initializing is a good manner
        $scope.currtab= tabs?tabs[0] : {};//当前选中的tab
        $scope.tabs = tabs;
        //tab index
        var watchIdx = function(){
            $scope.$watch('selectedIndex', function(current, old){
                if(current !== undefined){
                    //console.log('[info]#watch(\'#selectedIndex\') current is:'+current+",old:"+old);
                    selected = tabs[current];
                    setCurrTab( selected ) ;
                    $scope.services = [];
                    loadData(selected.value);
                    if( autoScale ){
                        autoScale( selected.value ) ;
                    }
                }else{
                    console.log('[Exception]selectedIndex undefined>current is:'+current+",old:"+old); //normally it can't happen
                }
            });
        }
        var loadData = function (clusterId) {
            k8sService.getServices(undefined,clusterId).then(function(result){
                $scope.services = result.data; //加载当前集群tab下的services
            }, function(err){
                if(!err || ! err.data ){
                    err = {
                        data:"Request timeout!"
                    }
                }
                alertify.error(err.data);
            });
        }
        $scope.init = function(){
            xenon_toggles_init();
        }

        //@RequestMapping('/cp/service') list of services
        $scope.currentPageServices = [];
        $scope.tabsub = {};
        $scope.tabsub.currentPage = 1;
        $scope.numPerPage = 10;
      $scope.currentServices={};
      $scope.searchText="";

      //watch the  $scope.services and  $scope.currentPage
        $scope.$watch("services + tabsub.currentPage", function(newValue, oldValue, scope) {
            //每次获取到数据就会触发这里
            if ($scope.services) {

                var serviceIndexMap = new Object();
                for (var i = 0; i < $scope.services.length; i++) {
                    serviceIndexMap[$scope.services[i].id] = i;
                }
                k8sService.listPodAutoScale(null, "default").then(function (result) {
                        if (Array.isArray(result.data)) {
                            result.data.forEach(function (s) {
                                var index = serviceIndexMap[s.name];
                                if (index != null && $scope.services[index] != null) {
                                    $scope.services[index].scalerEnabled = true;
                                }
                            });
                        }
                    },
                    function (err) {
                        alertify.error("list error:" + err.data);
                    });

                newValue = newValue || "" ;
                var begin = (($scope.tabsub.currentPage - 1) * $scope.numPerPage)
                    , end = begin + $scope.numPerPage;
              $scope.currentServices = $scope.services.slice(begin, end);//slice 切成片; 切下; 划分;

              $scope.currentServices.forEach(function(service) {
                    //init
                    if($rootScope[service.app] == undefined)
                        $rootScope[service.app] = {};

                    service.updateEnabled =  service.dbJson.updateEnabled || false;
                    setServiceIconAndLoop(service);
                })
              if($scope.searchText == ""){
                $scope.currentPageServices = $scope.currentServices;
              }else{
                $scope.currentPageServices = $filter('filter')($scope.services, {'app': $scope.searchText})
                $scope.currentPageServices.forEach(function(service) {
                  //init
                  if($rootScope[service.app] == undefined)
                    $rootScope[service.app] = {};

                  service.updateEnabled =  service.dbJson.updateEnabled || false;
                  setServiceIconAndLoop(service);
                })
                $scope.$emit('getPodStatusWhenRunning',$scope.currentPageServices);
              }

                if( newValue && newValue.indexOf("[object Object]") !== -1 ){
                    //确保是services发生变化了，而不是tab
                    $scope.$emit('getPodStatusWhenRunning',$scope.currentServices);
                }
            }
        });
      $scope.searchPageHide=false;
      $scope.searchClick=function () {
        if ($scope.searchText == "") {
          $scope.searchPageHide=false;
          $scope.currentPageServices = $scope.currentServices;
        } else {
          $scope.searchPageHide=true;
          $scope.currentPageServices = $filter('filter')($scope.services, {'app': $scope.searchText})
          $scope.currentPageServices.forEach(function(service) {
            //init
            if($rootScope[service.app] == undefined)
              $rootScope[service.app] = {};

            service.updateEnabled =  service.dbJson.updateEnabled || false;
            setServiceIconAndLoop(service);
          })
          $scope.$emit('getPodStatusWhenRunning',$scope.currentPageServices);
        }
      };
        //loadData();
        $scope.createService = function () {
            //跳转到镜像选择界面,并且传递当前的tab页面（集群信息）
            $state.go("cp.servicecreate",{"currtab":$scope.currtab});
        }
        //启动或者停止服务
        $scope.operator = function (e,svc) {
            e.stopPropagation();
            clearEvents(svc.app) ;
            $scope.status =   svc.totalStatue ;//record the status of current service
            if( svc.totalStatue === 'stop'){//TODO status = error
                svc.totalStatue = 'starting';
                startSvc(svc);
            }
            else if(svc.totalStatue === 'running' || svc.totalStatue === 'restarting' || svc.totalStatue === 'error'){
                svc.totalStatue = 'stoping';
                stopSvc(svc);
            }

        };


        //重启服务
        $scope.restart = function (e,svc) {
            e.stopPropagation();
            $scope.status =  svc.totalStatue;
            clearEvents(svc.app) ;
            if( svc.totalStatue !== 'restarting' && svc.totalStatue !== 'updating' ){
                if( svc.totalStatue === 'starting' || svc.totalStatue === 'stoping'){
                    alertify.error(" need to wait previous operator finished");
                }else{
                    svc.totalStatue = 'restarting';
                    restartSvc(svc);
                }
            }else{
                alertify.error('need to wait previous operator finished');
            }
        };

        $scope.superStop = function(e,svc){
            e.stopPropagation();
            if( svc.totalStatue && svc.totalStatue.indexOf("stop") !== -1){
                return ;
            }
            svc.totalStatue = 'stoping';
            clearEvents( svc.app) ;
            if(_getPodst_to !== undefined)
                clearTimeout(_getPodst_to);
            if(_podTracer !== undefined){
                clearTimeout(_podTracer);
                _podTracer = undefined ;
            }
            stopSvc(svc,true);

        }
        //open img version windows
        $scope.openVer = function (e,data) {
            e.stopPropagation();
            clearEvents(data.app) ;
            //console.log("#openVer:"+data.app+",currentApp "+$scope.currentApp +",") ;
            if(data.totalStatue === 'running'){
                var TestVerPer=null;

                $http({
                    url:'/trafficRule/get',
                    method:'POST',
                    data:{
                        "serviceName":data.id,
                        "version":data.imageVersion
                    }
                }).success(function(d,header,config,status){
                    data.TestVerPer=Number.parseInt(d);
                    var modalInstance = $uibModal.open({
                        animation: $scope.animationsEnabled,
                        templateUrl: 'template/cp/versionModal.html',
                        controller: 'VerModifyController',
                        resolve: {
                            data: function () {
                                return data;
                            }
                        }
                    });

                    modalInstance.result.then(function (selectedItem) {
                        clearEvents(data.app) ;
                        $scope.selected = selectedItem;
                    }, function () {
                        //$log.info('Modal dismissed at: ' + new Date());
                    });
                }).error(function(data,header,config,status){

                });

            }else{
                alertify.error('gray update only in service running status');
            }
        };

        $scope.scale = function (e,data) {
            e.stopPropagation();
            clearEvents(data.app) ;
            if(isServiceInMidStatus(data) === false){

                //}
                //if(data.totalStatue !== 'stop'){
                //stopPolling();
                var modalInstance = $uibModal.open({
                    animation: $scope.animationsEnabled,
                    templateUrl: 'template/cp/scaleModal.html',
                    controller: 'ModifyReplicasCtrl',
                    resolve: {
                        data: function () {
                            return data.dbJson;
                        }
                    }
                });

                modalInstance.result.then(function (selectedItem) {
                    //console.log("[debug][scale] selectedItem:"+JSON.stringify(selectedItem)) ;
                    data.dbJson = selectedItem;
                    data.totalStatue = selectedItem.totalStatue;
                    console.log("after scale status is:"+data.totalStatue);
                    data.ver = selectedItem.ver ;
                    setServiceIconAndLoop(data);
                }, function () {

                });
            }else{
                //alertify.alert('Service Operation','只有在运行的状态下才能操作！');
                alertify.error('need to wait previous operator finished');
            }
        }
        $scope.autoScale = function (e,data) {
            e.stopPropagation();
        };
        $scope.autoDeploy = function (e,data) {
            e.stopPropagation();
        };

        $scope.toggleAnimation = function () {
            $scope.animationsEnabled = !$scope.animationsEnabled;
        };

        $scope.$on('$destroy', function(){
            if (angular.isDefined(promise)) {
                $interval.cancel(promise);
                promise = undefined;
            }

            //unsubscribe event
            if(_deregister_udp_info !== undefined)
                _deregister_udp_info();
        });
        //---events----
        $scope.hideMe =function(){

            $mdBottomSheet.hide();
        }
        $scope.currentApp = undefined ;
        $scope.items = [ ];
        $scope.pods = {} ; //事件缓存

      //事件缓存变更，则更新当前items
        $scope.$watch("pods", function() {
          if ($scope.pods && $scope.currentApp) {
                //每次获取到数据就会触发这里
                if(  !$scope.pods[ $scope.currentApp] ){
                    $scope.pods[ $scope.currentApp] = [] ;
                    $scope.pods[  $scope.currentApp ].push({
                        "uid":"404",
                        "reason":"NoData",
                        "message":$scope.currentApp+" 暂无新事件 "
                    });
                }
                //items 更新
                $scope.items = $scope.pods[ $scope.currentApp ] ;

            }else{
                //can't find currentApp
                //console.log("error:$scope.currentApp="+$scope.currentApp) ;
            }

        } ,true );
        /**
         * 获取Pod的事件信息
         * ps:
         * 1.Pod会经常被 重建
         * 2.ETCD会清理过期的Events
         * 3.假如后台创建有延迟，则会取到原来pod的events
         */
        $scope.getHistoryStatus = function(item){
          if (item!==undefined&&item.lastState) {
            if (item.lastState.terminated) {
              delete item.lastState.terminated.containerID;
              delete item.lastState.terminated.finishedAt;
              delete item.lastState.terminated.startedAt;
            }
            var historyStatus = {
              lastState: item.lastState
            }
            $scope.tabs.historyStatus = jsyaml.safeDump(historyStatus).toString();
          }else{
            var historyStatus = {
              lastState: {}
            }
            $scope.tabs.historyStatus = jsyaml.safeDump(historyStatus).toString();
          }
        }

        $scope.getPodEvents = function(podName,clusterId,app ){
            if($scope.curPod.metadata!==undefined && podName!==$scope.curPod.metadata.name){
              return;
            }
            k8sService.getPodEvents( podName ,clusterId).then(function(result){
              $scope.pods[app] = [];

              if( result.code == 0 && result.data.length > 0 ){
                    var events = result.data ; //array
                    if( $scope.pods[app]  && $scope.pods[app].length !=0){
                      //append events to the event list
                        events.forEach(function(r){
                            //remove duplicated events
                            var code = hashCode( r.message ) ;
                            //console.log( code+"><"+r.message +">"+hashMap.get(code) ) ;
                            //if( !hashMap.contains( code )){
                                $scope.pods[app].push(  r  ) ;

                        }) ;
                    }else{
                        //initiate ,assign values when pod.events are empty
                        clearEvents(app) ;
                        //put events into pod's event list and go through the map to avoid the repeated events
                        events.forEach(function(r){
                            var code = hashCode( r.message ) ;
                            //if( !hashMap.contains( code )){
                                $scope.pods[app].push(  r  ) ;
                              //  hashMap.set( code ,true ) ;
                            //}
                        }) ;
                        // $scope.pods[app] = events ;
                    }

              }else{
                    if( !$scope.pods[app]){
                        console.log("No pod[app] exists.") ;
                        $scope.pods[app] = [] ;
                    }
                    if($scope.pods[app][0]!==undefined){
                      return;
                    }
                    $scope.pods[app].push({
                        "uid":"404",
                        "reason":"NoData",
                        "message":podName+" 暂无新事件 "
                    });
                    console.log(app+" getPodEvents:"+ JSON.stringify( result )   ) ;
                }

            }, function(err){
                alertify.error("Can not get pod  events !") ;
                console.log( "Can't get events ,"+err ) ;
            });
        }
        $scope.svc={};
        $scope.showLogs = function(e,svc) {
          $scope.svc=svc;

          e.stopPropagation();
          /*var width=jQuery('.sidebar-menu').css("width");
          setTimeout(function () {
            jQuery('.md-has-header').css("margin-left",parseInt(width)+50)
          },10)*/
            //console.log("showLogs->"+ svc.app) ;
            $scope.currentApp = svc.app  ;  //确定当前服务为需要查询的对象
            $scope.items = $scope.pods[ $scope.currentApp ] ;

          if( svc.totalStatue == 'running' || svc.totalStatue == 'stop'||  svc.totalStatue == 'error'){
                //refresh
                clearEvents($scope.currentApp ) ;
            }

          k8sService.getpodStatus(svc.dbJson).then(function (ret) {
              $scope.projects=ret.data.items;
              // console.log($scope.projects);
              // console.log(ret)
              // console.log($scope.projects)
              // console.log($scope.items);
              $scope.curPod=$scope.projects[0];
              },
            function(){
              // alertify.error('get pod error');
            });
          //getpodstatus($scope.svc,pullEvents,$scope.curPod) ; //avoid data cleared ,pull once when open the events panel

          //$scope.getPodEvents($scope.curPod,clusterId,app )
            showEventPanel() ;
        };
      $scope.$watch("curPod",function (new_val,old_val) {
          if(!isOwnEmpty($scope.curPod)) {
              $scope.getHistoryStatus($scope.curPod)
              getpodstatus($scope.svc, pullEvents, $scope.curPod); //avoid data cleared ,pull once when open the events panel
          }
      })

        function isOwnEmpty(obj)
        {
            for(var name in obj)
            {
                if(obj.hasOwnProperty(name))
                {
                    return false;
                }
            }
            return true;
        };

        $scope.clickService = function (data) {
            $state.go("cp.servicedetail",{
                service:data,
                clusterId:data.dbJson.node.clusterId,
                serviceName: data.app
            });
            // cp.servicedetail({service:data, clusterId:data.dbJson.node.clusterId ,serviceName: data.app})
        };


        function loadClusterInfo(){
            clusterService.getClustersInfo().then(function(result){
                //通过sessionStorage记住当前选中的tab
                if( existSessionStorage() && $scope.selectedIndex === 0 ){
                    var index = window.sessionStorage.getItem("selectedIndex" ) ;
                    if( index ){
                        $scope.selectedIndex = parseInt(index);
                    }
                }
                result.data.forEach(function(cluster){
                    if( $stateParams.clusterId !== null && $stateParams.clusterId === cluster.clusterId ){
                        var _idx = result.data.indexOf(cluster) + 1;//default tab is default cluster ,so other cluster's index must >0
                        console.log('set index is:'+_idx);
                        $scope.selectedIndex = _idx;
                    }
                    // 加载集群tab
                    tabs.push({title:cluster.name,value:cluster.clusterId});
                });
                watchIdx();
            },function(err){
                console.log("[error]loadClusterInfo:"+JSON.stringify( err ) ) ;
                if( !err.data || err.data ==null ){
                    err = {
                        data:"request time out!"
                    }
                }else{
                    err = {
                        data:"Can not get data !"
                    }
                }
                alertify.alert('query clusters err', err.data);
            });
        }

        //回调接口，获得Pod信息后回调本接口，将Pod信息传回来
        function pullEvents( status ){
          $scope.pods={}
            if( status && status.length > 0 ){
                for(var pod in status ){
                    var podName = status[pod].replicasname ; //pod is index
                    var app = status[pod].app ;
                    var clusterId = status[pod].clusterId ;
                    $scope.getPodEvents(podName,clusterId,app ) ;
                }
            }else{
                $scope.pods[$scope.currentApp] = [];
                $scope.pods[  $scope.currentApp ].push({
                    "uid":"404",
                    "reason":"NoPod",
                    "message":$scope.currentApp+"暂无容器运行"
                });
                console.log( "pull-pod callback: no pods exist")   ;
            }
        }

        function clearEvents(app) {
            reloadFalse() ;
            $scope.currentApp = app ;
            $scope.pods[ app] = [] ;
            hashMap.clear();
        }

        function showEventPanel(){
            $mdBottomSheet.show({
                templateUrl: 'template/cp/servicePodEvents.html',
                controller: 'ListBottomSheetCtrl',
                scope: $scope,
                preserveScope:true,
                parent:'#right-container'
            }).then(function(clickedItem) {
                //, parent:'#listPanelContainer'
                //alertify.success(  clickedItem['name']  );
            });
        }

        function getState(obj){
            for (var st in obj) {
                return st;
            }
        }

        /**
         * 1.更改Rc状态，
         * 2.更改DB状态
         * 3.更改页面按钮显示状态
         * @param svc
         */

        function startSvc(svc){
            k8sService.startService(svc.dbJson).then(function (r) { //resolve
                if(r.ret == true){//rc 设置成功
                    k8sService.updateServiceStatus(svc,"starting").then(function(){
                        setServiceIconAndLoop(svc);
                    },function(){
                        //update db error
                        //need to retry, or the status in db and in k8s is conflicting
                        console.log("[Error]appConfigEnv status update failed!") ;
                        resetServiceStatus(svc);
                    });
                }else{
                    if( r == undefined ){
                        var r = {
                            "data":"Failed to start service "+svc.app
                        };
                    }
                    alertify.error("service start error :" + r.data);
                    resetServiceStatus(svc) ;
                }
            }, function (r) {//reject
                if( r == undefined ){
                    var r = {
                        "data":"Failed to start service "+svc.app
                    };
                }
                alertify.error("service start error : "+ r.data);
                resetServiceStatus(svc) ;
            });
        }

        function stopSvc(svc,force){
            k8sService.stopService(svc.dbJson,force).then(function (r) {
                if(r.ret == true){
                    k8sService.updateServiceStatus(svc,svc.totalStatue).then(function(){
                        setServiceIconAndLoop(svc);
                    },function(e){
                        //update db error
                        //need to retry
                        resetServiceStatus(svc) ;
                        alertify.alert("service stop error" );
                    });
                }
            }, function (r) {
                alertify.alert("service stop error", r.error);
            });
        }
        /**
         * 重启服务
         * 1.更新数据状态
         * 2.给监听器发送重启事件
         * @param svc
         */
        function restartSvc(svc){

            k8sService.updateServiceStatus(svc,"restarting").then(function(){
                setServiceIconAndLoop(svc);
            },function(){
                console.log("updateServiceStatus.failed") ;
                restartUgly(svc) ;
                resetServiceStatus(svc) ;
                alertify.alert("service restart error" );
                //update db error
                //need to retry
            });
        }

        /**
         * 向Api-Server请求Pod的创建信息
         * cb,callback
         */
        function getpodstatus(svc,cb,podId){
            svcCommonService.getpodstatus(svc,cb,podId);
        }

        function setServiceIconAndLoop(service,data){
            svcCommonService.setIconClass(service); //set icons
            setRunningNum(service);                 //set instances numbers
            setStatusToDo(service,data);            //set sign to trigger the events
        }
        //设置当前运行的服务数目
        function setRunningNum(service){
            //console.log(service);
            switch (service.totalStatue){
                case 'error':
                    getpodstatus(service,setRunningNum);
                    break;
                case 'stop':
                    service.runningNum = 0;
                    break;
                case 'running':
                    getpodstatus(service,setRunningNum);
                    //service.runningNum = service.dbJson.rcnum;
                    break;
                case 'starting':
                case 'stoping':
                case 'restarting':
                case 'scaling':
                    getpodstatus(service,setRunningNum);
                    break;
                default:
                    console.log("Unknow service status:" + service.totalStatue  ) ;
                    break;
            }

            function setRunningNum(status){
                var _runningNum = 0;
                for(var k=0;k< status.length;k++){
                    if(status[k].phase === 'running')
                        _runningNum++;
                }
                service.runningNum = _runningNum;
            }
        }
        //根据当前服务状体，传递事件,让监听对应状态的观察者执行更新
        function setStatusToDo(service,data){
            switch (service.totalStatue){
                case 'starting':
                    if($rootScope[service.app].start !== true)
                        $scope.$emit('getPodStatusWhenStart',service);
                    break;
                case 'stoping':
                    if($rootScope[service.app].stop !== true)
                        $scope.$emit('getPodStatusWhenStop',service);
                    break;
                case 'restarting':
                    if($rootScope[service.app].restart !== true){
                        //don't know why add svc wrapper
                        if(data !== undefined){
                            $scope.$emit('getPodStatusWhenRestart',{svc:service,cb:data.cb});
                        }else
                            $scope.$emit('getPodStatusWhenRestart',{svc:service});
                    }

                    break;
                case 'updating':
                    if($rootScope[service.app].updating !== true)
                        $scope.$emit('getPodStatusWhenUpdate',service);
                    break;
                case 'scaling':
                    if($rootScope[service.app].scaling !== true)
                        $scope.$emit('getPodStatusWhenScale',service);
                    break;
                default:
                    console.log("No operation for "+service.totalStatue) ;
                    break;
            }

        }

        function broadcast(service){
            //ServiceOperatorNavController will watch this event.
            $rootScope.$emit('updateServiceStatus',service);
        }

        function isServiceInMidStatus(service){
            return svcCommonService.isServiceInMidStatus(service);
        }

        function findServiceById(service){
            var _svc = undefined;
            for(var i=0 ; i<$scope.services.length; i++ ){
                if($scope.services[i].app === service.app){
                    _svc = $scope.services[i];
                    break;
                }
            }
            return _svc;
        }

        $scope.$on('getPodStatusWhenStart',function(event,svc){
            $rootScope[svc.app].start = true;
            getpodstatus(svc,setStartStatus);//pull status again

            /**
             * change status in db and page.
             */
            function setStartStatus(status ,svc ){
                setServiceStatus(svc,status,"start") ;
            }
        })

        $scope.$on('getPodStatusWhenStop',function(event,svc){
            $rootScope[svc.app].stop = true;
            getpodstatus(svc,setStopStatus);

            function setStopStatus(status) {
                setServiceStatus(svc,status,"stop") ;
            }

        })
        /**
         * 监听重启事件
         */
        $scope.$on('getPodStatusWhenRestart',function(event,data){
            //console.log("getPodStatusWhenRestart#svc={" + data.cb +","+data.svc+"}"  ) ;
            var svc = data.svc;
            var callback = data.cb;
            $rootScope[svc.app].restart = true;

            if(data.fn !== undefined){
                data.fn(svc);
            }else if(callback !== undefined){
                getpodstatus(svc,callback);
            }  else{ //default begin is stop service
                _stop(svc);
            }

            var getStopStatus =  function(status){
                var _scope = $rootScope.curScope;
                var _idx = $scope.services.indexOf(svc);
                var _curSvc = _scope.services[_idx] || {};

                if( _curSvc.totalStatue=="restarting"&& status.length> 0 &&status[0].phase ==="running"){
                    status = [] ;
                }
                //need to req again
                //假如在等待停止的时候刷新了一些页面，就会导致页面状态不正确
                if(status.length > 0
                    && status[0].phase !== 'Failed'){
                    _curSvc.runningNum = status.length;
                    _getPodst_to = setTimeout(function(){
                        $scope.$emit('getPodStatusWhenRestart',{svc:svc,cb:getStopStatus});
                    },2000);
                }
                else{
                    _curSvc.runningNum = 0;
                    //start service after stop
                    $scope.$emit('getPodStatusWhenRestart',{svc:svc,fn:_start});
                }
            }
            $scope.stopStatus = getStopStatus;
            /**
             * 设置启动的状态，孪生兄弟方法：setStartStatus(status) T_T
             * @param status
             */
            var getStartStatus= function(status){
                setServiceStatus(svc,status,"restart") ;
            }
            $scope.getReStartStatus = getStartStatus ;
            function _start(svc){
                if(svc !== undefined){
                    k8sService.startService(svc.dbJson).then(function (r) {
                        if(r.data == true){
                            $scope.$emit('getPodStatusWhenRestart',{svc:svc,cb:getStartStatus});
                        }else{
                            console.log("startService failed ,no valid service running!") ;
                            alertify.error(" start error "+ r.data + " when service restart");
                            restartUgly(svc)
                            resetServiceStatus(svc,true) ;
                        }
                    }, function (r) {
                        console.log("startService failed"+JSON.stringify( r ) ) ;
                        alertify.error(" start error "+ r.data + " when service restart");
                        restartUgly(svc) ;
                        resetServiceStatus(svc,true) ;
                    });
                }else{
                    console.log("_start failed , no svc allocated!") ;
                }
            }
            /**
             * 停止服务
             */
            function _stop(svc){
                if(svc !== undefined) {
                    k8sService.stopService(svc.dbJson).then(function (r) {
                        if (r.data == true) {
                            $scope.$emit('getPodStatusWhenRestart', {svc: svc, cb: getStopStatus});
                        }
                    }, function (r) {
                        alertify.error(" stop error "+ r.data+" when service restart");
                    });
                }
            }

        })

        $scope.$on('getPodStatusWhenUpdate',function(event,svc){
            $rootScope[svc.app].updating = true;
            getpodstatus(svc,setStartStatus);

            function setStartStatus(status ,svc ){
                setServiceStatus(svc,status,"update");
            }
        })

        $scope.$on('getPodStatusWhenScale',function(event,svc){

            $rootScope[svc.app].scale = true;

            getpodstatus(svc,setStartStatus);

            function setStartStatus(status,svc){
                setServiceStatus(svc,status,"scale") ;
            }
        })

        $scope.$on('getPodStatusWhenRunning',function(event,currentPageServices){
            var time = 3500 ;

            /**
             * 确保running状态的服务因为运行时发生的错误停止或者error状态
             * 能够及时与页面保持一致性
             */
            if( currentPageServices ){
                var currentServices = currentPageServices ;

                currentServices.forEach(function(service) {
                    if( service.totalStatue === "running"
                        || service.totalStatue === "error"  ){
                        //console.log("running:"+service.app ) ;
                        getpodstatus( service ,setRunningStatus);
                    }
                }) ;

                var eventHandler = function(){
                   //console.log("Tick..");
                        $scope.$emit('getPodStatusWhenRunning',currentServices);
                        $scope._podTracerCount++ ;
                }
                if( $scope._podTracerCount !=undefined && $scope._podTracerCount < 1 ){
                    _podTracer = setTimeout(eventHandler,time );
                }
            }

            //通过runOnce的行为让下面的状态调整方法来调整状态
            //状态变更:
            //    1.->返回，nop，等待下次执行
            //    2.->更改界面显示->更改数据库状态
            function setRunningStatus(status,svc){
                var op ="runOnce" ;

                if( status && status.length > 0 ){
                    var clone = objClone(svc)  ;
                    setServiceStatus( clone ,status, op ) ;
                }else if( svc.totalStatue !== "stop"  ){
                    //没有运行中的pod ，设置为error（一般服务都会设置为RestartPolicy=always）
                    svc = svc || {
                        dbJson:""
                    } ;
                    svc.totalStatue = "error";
                    var _scope = $rootScope.curScope;
                    var _st = svc.totalStatue;
                    var _idx = $scope.services.indexOf(svc);
                    var _curSvc = _scope.services[_idx];
                    console.log("[ERROR]No pod running  !");
                    changeStatusOf( _curSvc ,svc ,_st,op ) ;
                }
            }
        })

        function objClone(obj){
            return utilService.deepCopyObj(obj ) ; ;
        }

        function restartUgly(svc){
            $rootScope[svc.app].restart = false ;
            svc.totalStatue = 'stop' ;
            console.log("restartUgly.svc.totalStatue:"+svc.totalStatue) ;
        }
        /**
         *  1.改回原来的状态
         *  2.刷新界面
         *  3.酱数据库中的状态也rollback
         */
        function resetServiceStatus(service,update){
            //console.log("roll back the status and refresh!"+$scope.status) ;
            if( $scope.status){
                //rollback db,必须要把状态变更回来，不然会导致数据库状态不一致
                if( update && update === true  ){
                    k8sService.updateServiceStatus(service, $scope.status ).then(function (data) {
                        console.log("Rollback the status !!!") ;
                    }, function (e) {
                        alertify.alert("Error","Can not update the status in appConfigEnv!") ;
                        if(e){
                            console.log("Rollback the status !!!"+JSON.stringify( e )) ;
                        }
                    });
                }
                service.totalStatue = $scope.status ;
            }
            setServiceIconAndLoop(service);
        }
        function hashCode(str) {
            if( !str ) return 0;
            var h = 0;
            var len = str.length;
            var t = 2147483648;
            for (var i = 0; i < len; i++) {
                h = 31 * h + str.charCodeAt(i);
                if(h > 2147483647) h %= t;//java int溢出则取模
            }
            /*var t = -2147483648 * 2;
             while (h > 2147483647) {
             h += t
             }*/
            return h;
        }
        function myrefresh() {
            // setTimeout(function(){
            //     window.location.reload();
            // },3000);
        }
        function setCurrTab(selected) {
            if( existSessionStorage() ){
                window.sessionStorage.setItem("selectedIndex", $scope.selectedIndex);
            }
            $scope.currtab = selected ;
        }
        function reloadFalse(){
            $scope.reloaded = false ;
        }
        //if sessionStorage supported
        //sessionStorage is feature of html5 ,so may be some navigator can't support
        function existSessionStorage(){
            if(window.sessionStorage){
                return true ;
            }
            return false ;
        }
        function refreshf5(){
            document.onkeydown = function (e) {
                var ev = window.event || e;
                var code = ev.keyCode || ev.which;
                if (code == 116) {
                    ev.keyCode ? ev.keyCode = 0 : ev.which = 0;
                    cancelBubble = true;
                    alert("Don't fresh");
                    return false;
                }
            } //禁止f5刷新
            document.oncontextmenu=function(){
                alert( "Don't fresh" );
                return false
            };//禁止右键刷新

        }
        //refreshf5() ;
        _deregister_udp_info = $rootScope.$on('udpSvcInfoWhenUpdate',function(event,data){
            if($scope.services.indexOf(data) === -1){
                //console.log("_cur:"+JSON.stringify(_svc)) ;
                var _svc = findServiceById(data);
                _svc.totalStatue = data.totalStatue;
                if(data.totalStatue === 'running'){
                    _svc.ver = data.ver;
                    _svc.imageversion = data.imageversion;
                    _svc.dbJson.ver = data.dbJson.ver;
                    _svc.dbJson.rc = data.dbJson.rc;
                }
                //svcCommonService.setIconClass(_svc);
                setServiceIconAndLoop( _svc ,{} ) ;
            }
            //trigger call getPodStatusWhenUpdate
            else{
                $scope.$emit('getPodStatusWhenUpdate',data);
            }

            //console.log($scope.services.indexOf(data));
        });

        var operation={
            "stop":"stoping",
            "start":"starting",
            "restart":"restarting",
            "update":"updating",
            "scale":"scaling",
            "runOnce":"runOnce"
        } ;
        function setServiceStatus(svc,status,op){
                var _scope = $rootScope.curScope;
                var _idx = $scope.services.indexOf(svc);
                var _curSvc = _scope.services[_idx];
                var temStatus = svc.totalStatue ;

                if(_curSvc === undefined){
                    _curSvc = svc;
                }
                if( _curSvc === undefined ){
                    console.log("Something error happened!!!") ;
                    return ;
                }

                if( _curSvc.totalStatue ==="updating" || op =="update" ){
                    //避免更新中pod暂时重启
                    if( !status || status.length == 0 ){
                        //只要pod未启动就需要继续运行
                        $scope.$emit('getPodStatusWhenUpdate',svc );
                    }
                }

                if( _curSvc.totalStatue ===operation[op] || op == operation[op] ){
                    svc.totalStatue = operation[op];
                    var _runningNum = 0;
                    var finalStatus = "" ;
                    for(var k=0;k< status.length;k++){
                        if( "runOnce" !== op && svc.app === $scope.currentApp ){
                            //减少时间的跟踪对象，只限于当前的app
                            $scope.getPodEvents( status[k].replicasname ,svc.dbJson.node.clusterId,svc.app) ;
                        }
                        if( op ==="stop"){
                            continue ;
                        }

                        if(status[k].phase === 'Pending'|| status[k].phase === 'starting' )
                            svc.totalStatue = 'starting';
                        else if(status[k].phase === 'Error'  ){
                            svc.totalStatue = 'error';
                            finalStatus =  'error';
                            console.log("[Warn]"+status[k].replicasname+" failed!") ;
                        }else if( status[k].phase === 'terminated' || status[k].phase === 'Terminating'  ) {
                            svc.totalStatue = 'stop';
                        }else if(status[k].phase === 'running')
                            _runningNum++;
                        else
                            svc.totalStatue = operation[op];
                    }
                    if( op ==="stop"){
                        _runningNum =  status.length;
                        if(status.length > 0 ){
                            svc.totalStatue = operation[op] ;//stoping
                        }else{
                            svc.totalStatue =  op ;
                        }
                    }else if( op === "scale" ){
                        /**
                         *  service scale down may return pods number larger than rc num
                         *  ( "Terminating" pod will also return in status list )
                         */
                        if(status.length >= _runningNum && _runningNum  == _curSvc.dbJson.rcnum){
                            svc.totalStatue = 'running';
                        }

                    }else{
                        if(status.length === _runningNum && _runningNum !== 0 && _runningNum  >= _curSvc.dbJson.rcnum){
                            svc.totalStatue = 'running';
                        }
                    }
                    if( _runningNum == 0 && finalStatus === 'error'){
                        //所有的pod都失败了
                        svc.totalStatue = 'error';
                    }else if( _runningNum < _curSvc.dbJson.rcnum && finalStatus === 'error'){
                        //部分pod失败，定义为不健康的
                        svc.totalStatue = 'starting';
                    }
                    if( op !== "runOnce"){
                        _curSvc.runningNum = _runningNum;
                    }

                    //need to req again
                    if(svc.totalStatue === operation[op] ){
                        if( op === "runOnce"){
                            console.log("run once");
                            //避免页面出现runOnce这种临时状态
                            svc.totalStatue = temStatus;
 ;                            return ;
                        }
                        var event = "" ;
                        var time = 1500 ;
                        var data = svc ;
                        switch(op){
                            case 'stop':
                                event = "getPodStatusWhenStop";
                                time = 2000 ;
                                break;
                            case 'start':
                                event = "getPodStatusWhenStart";
                                break;
                            case 'restart':
                                event = "getPodStatusWhenRestart";
                                data = {svc: svc, cb: $scope.getReStartStatus}
                                break;
                            case 'update':
                                event = "getPodStatusWhenUpdate";
                                break;
                            case 'scale':
                                event = "getPodStatusWhenScale";
                                break;
                            default:
                                console.log("Unknow operation status:" + op  ) ;
                                break;
                        }

                        var eventHandler = function(){
                            $scope.$emit( event , data );
                        }

                        _getPodst_to = setTimeout(eventHandler,time );
                    }else{
                        switch(op){
                            case 'stop':
                                $rootScope[svc.app].stop = false;
                                $rootScope[svc.app].stop = undefined;
                                svc.totalStatue = "stop" ;
                                break;
                            case 'scale':   //same as start
                                $rootScope[svc.app].scale = false;
                                $rootScope[svc.app].scale = undefined;
                            case 'start':
                                $rootScope[svc.app].start = false;
                                $rootScope[svc.app].start = undefined;
                                break;
                            case 'restart':
                                $rootScope[svc.app].restart = false;
                                $rootScope[svc.app].restart = undefined;
                                break;
                            case 'update':
                                $rootScope[svc.app].updating = false;
                                $rootScope[svc.app].updating = undefined;
                                break;
                            case 'runOnce':
                                if( svc.totalStatue === temStatus ){
                                   //状态与原来相同，就不需要更新数据库了
                                    return ;
                                }
                                break;
                            default:
                                console.log("[Store]Unknow operation status:" + op  ) ;
                                break;
                        }
                        var _st = svc.totalStatue;
                        var _idx = $scope.services.indexOf(svc);
                        _curSvc = _scope.services[_idx] || svc ;

                        changeStatusOf( _curSvc ,svc ,_st,op ) ;
                    }
                }
        }

        /**
         * 更改服务的显示状态，并且持久化
         */
        function changeStatusOf(_curSvc,newSvc,toStatus,op){
            var _st = toStatus || "";
            var svc = newSvc||{};
            op = op||"" ;

            if(_curSvc !== undefined) {
                _curSvc.totalStatue = _st;
                _curSvc.dbJson.totalStatue = _st;

                k8sService.updateServiceStatus(_curSvc, _curSvc.totalStatue).then(function (r) {
                   // console.log(""+JSON.stringify( r )) ;
                    if(_curSvc.totalStatue === 'running'||op ==="scale"){
                        //update the version after updated when operation is update
                        _curSvc.ver = svc.ver;
                        _curSvc.imageversion = svc.ver;
                        _curSvc.dbJson.ver = svc.ver;
                    }
                    //svcCommonService.setIconClass(_curSvc);
                    setServiceIconAndLoop( _curSvc ,{});
                    broadcast(_curSvc);
                    if(op !== "runOnce" ){
                        if( svc.totalStatue === "error" ){
                            alertify.error(op+" service [" + _curSvc.app + "] error" );
                        }else{
                            alertify.success(op+" service [" + _curSvc.app + "] over");
                        }
                    }

                    myrefresh() ;
                }, function () {
                    console.log("update db error")
                    //update db error
                    //need to retry
                });
            }//-
        }

        $scope.changeScalerStatus = function (service) {
            service.scalerChangePending = true;
            if (service.scalerEnabled) {
                k8sService.deletePodAutoScale({scaleName: service.id}, service.dbJson.node.clusterId).then(function (result) {
                        alertify.success("delete finished");
                        service.scalerChangePending = false;
                        service.scalerEnabled = false;
                    },
                    function (err) {
                        alertify.error("delete error:" + err.data);
                    });//alert("要关掉");
            }
            else {
                var autoScalerEntity = {
                    scaleName: service.id,     //自动伸缩组件名称（自定义）
                    max: 5,                      //能够伸缩最大pod数目
                    min: 1,                     //至少需要的pod数目
                    refKind: (service.dbJson.rc)?service.dbJson.rc.kind : service.dbJson.petset.kind, //基于组件进行控制伸缩（ReplicationController  ReplicationController Deploment）
                    refName: (service.dbJson.rc)?service.dbJson.rc.metadata.name : service.dbJson.petset.metadata.name,   //组件名称
                    cpuPct: 5,                   //cpu使用率百分比[0-100],-1表示取默认值80
                    clusterId: service.dbJson.node.clusterId             //集群id
                };
                k8sService.createPodAutoScale(autoScalerEntity, autoScalerEntity.clusterId).then(function (result) {
                        alertify.success("create finished");
                        service.scalerChangePending = false;
                        service.scalerEnabled = true;
                    },
                    function (err) {
                        alertify.error("create error:" + err.data);
                    });
            }
            console.log(service);
        }
        $scope.changeUpdateStatus= function (svc) {
           var market=svc.dbJson.node.isMarket;
            if(!market) {
                if (svc.updateEnabled) {
                    k8sService.Autoupdate(svc, !svc.updateEnabled).then(function (result) {
                            alertify.success("AutoUpdate has closed");
                        },
                        function (err) {
                            alertify.error("error:" + err.data);
                        });
                } else {
                    k8sService.Autoupdate(svc, !svc.updateEnabled).then(function (result) {
                            alertify.success("AutoUpdate has opened");
                        },
                        function (err) {
                            alertify.error("error:" + err.data);
                        });
                }
            }
        }
        $scope.delete = function (e,serverinfo) {
            e.stopPropagation();
            if(isServiceInMidStatus(serverinfo) === false){
                $mdDialog.show({
                    controller: function ($scope, $state, $mdDialog,params) {
                        $scope.sName=params.deleteInfo.app;
                        $scope.show=params.deleteInfo.dbJson.node.volumes.length>0?true:false;
                        $scope.isDelVolume=false;
                        $scope.ok=function () {
                            k8sService.deleteService(params.deleteInfo.dbJson,$scope.isDelVolume).then(function (ret) {
                                /*if (ret.data == true) {
                                    var _idx = params.serviceInfos.indexOf(params.deleteInfo);
                                    params.serviceInfos.splice(_idx,1);
                                    alertify.success("delete application success");
                                }*/
                                //not to go service list page if alert backgroud
                                //$state.go('cp.service');
                              $mdDialog.hide(ret);

                            }, function (err) {
                              $mdDialog.cancel(err);

                              // alertify.error('delete application error:'+ret.data);
                            });
                        }
                        $scope.cancel=function () {
                            $mdDialog.cancel();
                        }
                    },
                    templateUrl: 'serviceDel.html',
                    parent: angular.element(document.body),
                    targetEvent: e,
                    clickOutsideToClose: true,
                    fullscreen: true,// Only for -xs, -sm breakpoints.
                    locals: {
                        params: {
                            deleteInfo: serverinfo,
                            serviceInfos:$scope.services
                        }
                    }
                }).then(function (ret) {
                  if (ret.data == true) {
                    var _idx = $scope.services.indexOf(serverinfo);
                    $scope.services.splice(_idx,1);
                    alertify.success("delete application success");
                  }
                },function (err) {
                  if(err)
                    alertify.error('delete application error:'+err.data);

                })
            }else{
                alertify.error('need to wait previous operator finished');
            }
        };
    $scope.showVersion=function (ev,data) {
        ev.stopPropagation();
        clearEvents(data.app) ;
        if(data.totalStatue === 'running'){
            var TestVerPer=null;
            // $http({
            //     url:'/trafficRule/get',
            //     method:'POST',
            //     data:{
            //         "serviceName":data.id,
            //         "version":data.imageversion
            //     }
            // }).success(function(d,header,config,status){
                $mdDialog.show({
                    controller: 'VerModifyController',
                    templateUrl: 'versionChange.html',

                    parent: angular.element(document.body),
                    clickOutsideToClose: true,
                    fullscreen: true ,// Only for -xs, -sm breakpoints.
                    locals:{
                        params:{
                            data:data
                        }
                    }
                }).then(function (data1) {
                        clearEvents(data.app) ;
                        $scope.selected = data1;
                }, function () {
                    //$log.info('Modal dismissed at: ' + new Date());
                });
            // }).error(function(data,header,config,status){
            //
            // });

        }else{
            alertify.error('gray update only in service running status');
        }
    }
    $scope.showscale=function (ev,data) {
        ev.stopPropagation();
        clearEvents(data.app) ;
        if(isServiceInMidStatus(data) === false){
            $mdDialog.show({
                templateUrl: 'telescopicInstance.html',
                controller: 'ModifyReplicasCtrl',
                parent: angular.element(document.body),
                clickOutsideToClose: true,
                fullscreen: true ,// Only for -xs, -sm breakpoints.
                locals:{
                    params:{
                        data:data.dbJson
                    }
                }
            }).then(function (data1) {
                data.dbJson = data1;
                data.totalStatue = data1.totalStatue;
                console.log("after scale status is:"+data.totalStatue);
                data.ver = data1.ver ;
                setServiceIconAndLoop(data);
            })
        }else{
            //alertify.alert('Service Operation','只有在运行的状态下才能操作！');
            alertify.error('need to wait previous operator finished');
        }
    }
    $scope.showautoscale=function (ev,data,index) {
        ev.stopPropagation();
        $mdDialog.show({
            templateUrl: 'showServiceFlexModal.html',
            controller: function ($mdDialog,$scope,params) {
                // $scope.replicas=params.data.replicas?params.data.replicas:1;
                $scope.autoScalermax=params.data.dbJson.max?params.data.dbJson.max:5;
                $scope.scaler=params.data.dbJson.scalerEnabled?params.data.dbJson.scalerEnabled:false;
                $scope.autoScalercpu=params.data.dbJson.cpu?params.data.dbJson.cpu:5;
                $scope.ok=function () {
                    params.data.scalerChangePending = true;
                    if (!$scope.scaler) {
                        if (params.data.dbJson.scalerEnabled) {
                            k8sService.deletePodAutoScale({scaleName: params.data.id}, params.data.dbJson.node.clusterId,params).then(function (result) {
                                    alertify.success("delete finished");
                                    params.data.scalerChangePending = false;
                                    params.data.scalerEnabled = false;
                                    params.data.max = 5;
                                    params.data.cpu = 5;
                                },
                                function (err) {
                                    alertify.error("delete error:" + err.data);
                                });//alert("要关掉");
                        }else{
                            alertify.success("no change");
                        }
                    }
                    else {
                        var autoScalerEntity = {
                            scaleName: params.data.id,     //自动伸缩组件名称（自定义）
                            max: $scope.autoScalermax,                      //能够伸缩最大pod数目
                            refKind: (params.data.dbJson.rc) ? params.data.dbJson.rc.kind : params.data.dbJson.petset.kind, //基于组件进行控制伸缩（ReplicationController  ReplicationController Deploment）
                            refName: (params.data.dbJson.rc) ? params.data.dbJson.rc.metadata.name : params.data.dbJson.petset.metadata.name,   //组件名称
                            cpuPct: $scope.autoScalercpu,                   //cpu使用率百分比[0-100],-1表示取默认值80
                            clusterId: params.data.dbJson.node.clusterId             //集群id
                        };
                        if(params.data.scalerEnabled){
                            k8sService.deletePodAutoScale({scaleName: params.data.id}, params.data.dbJson.node.clusterId,params).then(function (result1) {
                                k8sService.createPodAutoScale(autoScalerEntity, autoScalerEntity.clusterId,params,$scope.scaler).then(function (result) {
                                        alertify.success("create finished");
                                        params.data.scalerChangePending = false;
                                        params.data.scalerEnabled = true;
                                        params.data.max=$scope.autoScalermax;
                                        params.data.cpu=$scope.autoScalercpu;
                                    },
                                    function (err) {
                                        alertify.error("create error:" + err.data);
                                    });
                            })
                        }else{
                            k8sService.createPodAutoScale(autoScalerEntity, autoScalerEntity.clusterId,params,$scope.scaler).then(function (result) {
                                    alertify.success("create finished");
                                    params.data.scalerChangePending = false;
                                    params.data.scalerEnabled = true;
                                    params.data.max=$scope.autoScalermax;
                                    params.data.cpu=$scope.autoScalercpu;
                                },
                                function (err) {
                                    alertify.error("create error:" + err.data);
                                });
                        }
                       }
                    $mdDialog.hide(params.data);
                }
                $scope.cancel=function () {
                    $mdDialog.cancel();
                }
            },
            parent: angular.element(document.body),
            clickOutsideToClose: true,
            fullscreen: true ,
            locals: {
                params: {
                    data: data
                }
            }
        }).then(function (data1) {
            $scope.currentPageServices[index].dbJson.max=data1.max;
            $scope.currentPageServices[index].dbJson.scalerEnabled=data1.scalerEnabled;
            $scope.currentPageServices[index].dbJson.cpu=data1.cpu;
        })
        // service.scalerChangePending = true;
        // if (service.scalerEnabled) {
        //     k8sService.deletePodAutoScale({scaleName: service.id}, service.dbJson.node.clusterId).then(function (result) {
        //             alertify.success("delete finished");
        //             service.scalerChangePending = false;
        //             service.scalerEnabled = false;
        //         },
        //         function (err) {
        //             alertify.error("delete error:" + err.data);
        //         });//alert("要关掉");
        // }
        // else {
        //     var autoScalerEntity = {
        //         scaleName: service.id,     //自动伸缩组件名称（自定义）
        //         max: 5,                      //能够伸缩最大pod数目
        //         min: 1,                     //至少需要的pod数目
        //         refKind: (service.dbJson.rc) ? service.dbJson.rc.kind : service.dbJson.petset.kind, //基于组件进行控制伸缩（ReplicationController  ReplicationController Deploment）
        //         refName: (service.dbJson.rc) ? service.dbJson.rc.metadata.name : service.dbJson.petset.metadata.name,   //组件名称
        //         cpuPct: 5,                   //cpu使用率百分比[0-100],-1表示取默认值80
        //         clusterId: service.dbJson.node.clusterId             //集群id
        //     };
        //     k8sService.createPodAutoScale(autoScalerEntity, autoScalerEntity.clusterId).then(function (result) {
        //             alertify.success("create finished");
        //             service.scalerChangePending = false;
        //             service.scalerEnabled = true;
        //         },
        //         function (err) {
        //             alertify.error("create error:" + err.data);
        //         });
        // }
    }
    $scope.showupdate=function (ev,data,index) {
        ev.stopPropagation();
        var market = data.dbJson.node.isMarket;
                $mdDialog.show({
                    templateUrl: 'automaticUpateing.html',
                    controller: function ($scope, params, $mdDialog) {
                        $scope.isMarket=data.dbJson.node.isMarket;
                        $scope.updateenable=params.data.updateEnabled?params.data.updateEnabled:false;
                        $scope.updatemarket=!$scope.isMarket&&!$scope.updateenable?true:false;
                        $scope.ok = function () {
                            k8sService.Autoupdate(params.data, !$scope.updateenable).then(function (result) {
                                    alertify.success("AutoUpdate has change");
                                    $mdDialog.hide(!$scope.updateenable);
                                },
                                function (err) {
                                    alertify.error("error:" + err.data);
                                    $mdDialog.hide();
                                });
                        }
                        $scope.cancel = function () {
                            $mdDialog.cancel();
                        }
                    },
                    parent: angular.element(document.body),
                    clickOutsideToClose: true,
                    fullscreen: true,// Only for -xs, -sm breakpoints.
                    locals: {
                        params: {
                            data: data
                        }
                    }
                }).then(function (data1) {
                    $scope.currentPageServices[index].updateEnabled=data1;
                })
    }
    });